package com.gethb.pub.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gethb.data.mdo.KlinesDo;
import com.gethb.data.mdo.TickerDo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.net.URL;
import java.util.List;

public class KLineDataUtils {

    static final String API_KEY = "e3588c0b-18eb35dc-frbghq7rnm-bf08b";
    static final String API_SECRET = "a4474864-0386d816-482975b9-76660";
    static final String HOST = "https://api.huobi.pro";
    static OkHttpClient okHttpClient = new OkHttpClient();

    public static List<KlinesDo> requestList(String symbol, String period, int size) throws Exception {

        String path = "/market/history/kline";
        UrlParamsBuilder builder = UrlParamsBuilder.build()
                .putToUrl("symbol", symbol)
                .putToUrl("period", period)
                .putToUrl("size", size);

        JSONObject jsonObject = request(path, builder);
        return JSON.parseArray(jsonObject.getJSONArray("data").toString(), KlinesDo.class);
    }

    public static TickerDo requestTicker(String symbol) throws Exception {

        String path = "/market/detail/merged";
        UrlParamsBuilder builder = UrlParamsBuilder.build()
                .putToUrl("symbol", symbol);

        JSONObject jsonObject = request(path, builder);
        return jsonObject.getObject("tick", TickerDo.class);
    }

    private static JSONObject request(String path, UrlParamsBuilder builder) throws Exception {
        String url = new URL(HOST).getHost();
        new OutBoundUtils().createSignature(API_KEY, API_SECRET, "GET", url, path, builder);

        String requestUrl = HOST + path + builder.buildUrl();
        Request executeRequest = new Request.Builder().url(requestUrl)
                .addHeader("Content-Type", "application/x-www-form-urlencoded").build();


        Response response = okHttpClient.newCall(executeRequest).execute();
        String respBody;
        if (response.code() == 200) {
            assert response.body() != null;
            respBody = response.body().string();
        } else {
            respBody = response.toString();
        }

        response.close();

        return JSON.parseObject(respBody);
    }
}
